
#include "Proactor.h"

#include <iostream>
using namespace std;

#define THIS_FILE	"Proactor"

int Proactor::HandleEvents(pj_time_val *timeout)
{
	pj_timer_heap_poll(th_, timeout);
	return pj_ioqueue_poll(ioqueue,timeout);
}

int Proactor::RegisterHandle(BaseSocket* p_sock)
{
	if (p_sock->GetSockType() == pj_SOCK_STREAM())
	{
		return pj_activesock_create(pool,p_sock->sock,pj_SOCK_STREAM(),
					NULL,ioqueue,&p_sock->cb,p_sock,&p_sock->p_asock);
	}
	else
	{
		return pj_activesock_create_udp(pool,&p_sock->addr,
					NULL,ioqueue,&p_sock->cb,p_sock,&p_sock->p_asock,NULL);
	}
}


Proactor::Proactor(int max_fd)
{
	cout << "Proactor ok!" << endl;
	pj_pool_factory *mem;
    pj_status_t status;
	status = pj_init();
    mem = &caching_pool.factory;
    pj_caching_pool_init( &caching_pool, NULL, 0 );
    pool = pj_pool_create(mem, THIS_FILE, 256, 256, NULL);
    status = pj_ioqueue_create(pool, max_fd, &ioqueue);
    if (status != PJ_SUCCESS) 
        return ;

    status = pj_timer_heap_create(pool,100, &th_);
}


Proactor::~Proactor()
{
		cout << "Proactor go!" << endl;
}


bool Proactor::DoTimer(BaseTimer* pTimer,pj_time_val delay)
{
	return pj_timer_heap_schedule(th_, &pTimer->timer_, &delay) == 0;
}

bool Proactor::UndoTimer(BaseTimer* pTimer)
{
	return pj_timer_heap_cancel(th_, &pTimer->timer_) == 1;
}
